//
//  RLFMDBModel.m
//  CodeFor链式编程
//
//  Created by relax on 2017/11/16.
//  Copyright © 2017年 relax. All rights reserved.
//

#import "RLFMDBModel.h"

@interface RLFMDBModel ()

@property (nonatomic,strong) FMDatabase *db;

@end

@implementation RLFMDBModel

- (instancetype)initWithDBPath:(NSString *)DBpath DBfileName:(NSString *)DBFileName {
    if (self = [super init]) {
        NSString *dbFilePath = [NSString stringWithFormat:@"%@/%@",DBpath,DBFileName];
        self.db = [FMDatabase databaseWithPath:dbFilePath];

        if (!self.db.open) {
            NSAssert(NO, @"数据库创建失败!");
        }
    }

    return self;
}

- (void)createTableName:(NSString *)name maker:(void(^)(RLFMDBMaker *))maker {
    if (!name) {
        NSAssert(NO, @"表名要正确!");
    }
    RLFMDBMaker *createTableMaker = [RLFMDBMaker new];

    createTableMaker.sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (*);",name];
    createTableMaker.db = self.db;
    maker(createTableMaker);
}


- (void)insertIntoTableName:(NSString *)tableName maker:(void (^)(RLFMDBMaker *))maker {
    if (!tableName) {
        NSAssert(NO, @"表名要正确!");
    }

    RLFMDBMaker *insertMaker = [RLFMDBMaker new];
    insertMaker.sql = [NSString stringWithFormat:@"INSERT INTO %@ (*) VALUES (?);",tableName];
    insertMaker.db = self.db;
    maker(insertMaker);
}

- (void)deleteFromTableName:(NSString *)tableName maker:(void (^)(RLFMDBMaker *))maker {
    if (!tableName) NSAssert(NO, @"表名要正确");

    RLFMDBMaker *deleteMaker = [RLFMDBMaker new];
    deleteMaker.sql = [NSString stringWithFormat:@"DELETE FROM %@",tableName];

    maker(deleteMaker);
}

- (void)updateFromTableName:(NSString *)tableName maker:(void (^)(RLFMDBMaker *))maker {
    if (!tableName) NSAssert(NO, @"表名要正确");

    RLFMDBMaker *make = [RLFMDBMaker new];
    make.sql = [NSString stringWithFormat:@"UPDATE %@",tableName];
    make.db = self.db;

    maker(make);
}

- (void)selectFromTableName:(NSString *)tableName maker:(void (^)(RLFMDBMaker *))maker result:(FMResultBlock)resultBlock {
    if (!tableName) NSAssert(NO, @"表名错误!");

    RLFMDBMaker *make = [RLFMDBMaker new];

    make.sql = [NSString stringWithFormat:@"SELECT * FROM %@ ",tableName];
    make.db = self.db;
    make.resultBlock = resultBlock;

    maker(make);
}

@end
